const Koa = require('koa')
const router = require('./routes')
const views = require('koa-views')  // 配置模板引擎
const path = require('path')
const static = require('koa-static') // 处理静态资源
const mongoose = require('mongoose')
const CONFIG = require('./config/config.js')
const session = require('koa-session')
const bodyParser = require('koa-bodyparser')
const flash = require('./middlewares/flash')


// 建立数据库连接
mongoose.connect(CONFIG.mongodb, (err, info) => {
  if (!err) {
    console.log('数据库连接成功');
  }
})

const app = new Koa()

app.use(views(path.resolve(__dirname, 'views'), {
  map: { html: 'nunjucks' }
}))
app.use(static(path.join(__dirname, 'public')))

// 创建session存储
app.keys = ['something']
app.use(session({
  key: CONFIG.session.key,
  maxAge: CONFIG.session.maxAge
}, app))

app.use(bodyParser())

app.use(async (ctx, next) => {
  ctx.state.ctx = ctx
  await next()
})

app.use(flash())

router(app)

app.listen(3000, () => {
  console.log('server is running at http://localhost:3000');
})





